////////////////// 配置相关信息开始 ////////////////////
var util = require("./util.js");
var getChildCategory = function(categoryId, globalCategoryName, callBack, showAll){
  wx.BaaS.getRecordList({
    tableID: getApp().globalData.TABLE_ID_CATEGORY,
    parent_id: getApp().globalData[categoryId]
  }).then( (res) => {
    var data = new Array();
    if(showAll) data.push({id: 0, name:'全部'});
    for(var i = 0; i < res.data.objects.length; i++){
      data.push({id: res.data.objects[i].id, name: res.data.objects[i].response.name});
    }
    getApp().globalData[globalCategoryName] = data;
    if(callBack) callBack(data);
  }, (err) => {
    console.log(err);
  });
}
////////////////// 配置相关信息结束 ////////////////////

var getClothList = function(that, isRefresh, topCategoryName){
  if(!isRefresh && that.data.pageNo != 0 && that.data.pageNo >= that.data.totalPage){
    that.setData({
          loadHide: true,
          filterCatHide:true,
          filterFiltHide:true
    });
    return;
  }
  that.setData({
      loadHide: false,
      filterCatHide:true,
      filterFiltHide:true
  });

  var pageNum = isRefresh ? 0 : that.data.pageNo; // 页码
  var limit = that.data.pageSize;
  var offset = limit * pageNum;
  var objects = {
    tableID: getApp().globalData.TABLE_ID_PRODUCT,
    status: 'valid',
    limit: limit,
    offset: offset
  };
  // 最新/最热
  var isNew = that.data.isNew;
  objects['order_by'] = isNew ? '-created_at' : '';

  // 分类
  if(topCategoryName){
    objects.category_id__in = getApp().globalData[topCategoryName]; 

    // 换成用户选择的分类
    if (that.data.catNo) objects.category_id__in = '' + that.data.catNo;
    if (that.data.selectedCatId) objects.category_id__in = '' + that.data.selectedCatId;

  }else{
    objects.category_id__in = getApp().globalData.RECOMMEND_CATEGORY_ID;
  }
  
  // if(that.data.catNo) objects.category_id__in += ',' + that.data.catNo;
  // if(that.data.selectedCatId) objects.category_id__in += ',' + that.data.selectedCatId;

  var massArr = new Array();
  var elasticityArr = new Array();
  // 筛选条件
  for(var i in that.data.selectedFilt){
    if(!that.data.selectedFilt[i]) continue;
    var tmpArr = i.split("_");
    if(tmpArr[0] == 'mass' || tmpArr[0] == 'elasticity') {
      // 面料的重量 和 弹力
      if(tmpArr[0] == 'mass') massArr.push(tmpArr[1]);
      if(tmpArr[0] == 'elasticity') elasticityArr.push(tmpArr[1]);
      continue;
    }
    if(tmpArr[0] && tmpArr[1]){
      var field = tmpArr[0];
      var value = tmpArr[1];
      if(typeof objects[field + '__in'] == 'undefined'){
        objects[field + '__in'] = value;
      }else{
        objects[field + '__in'] += ',' + value;
      }
    }
  }

  // 面料特殊处理
  // 如果有排序
  if(that.data.selectedOrderBy){
    objects['order_by'] = that.data.selectedOrderBy + ',' + objects['order_by'];
  }

  if(massArr.length){
    for(var i = 0; i < massArr.length; i++){
      if(massArr[i].substr(0,1) == '<'){
        objects['mass__lt'] = parseInt(massArr[i].substr(1));
      }else if(massArr[i].substr(0,1) == '>'){
        objects['mass__gt'] = parseInt(massArr[i].substr(1));
      }else if(massArr[i].substr(0,1) == 'r'){
        objects['mass__range'] = massArr[i].substr(1);
      }
    }
  }

  if(elasticityArr.length){
    for(var i = 0; i < elasticityArr.length; i++){
      if(elasticityArr[i].substr(0,1) == '<'){
        objects['elasticity__lt'] = parseInt(elasticityArr[i].substr(1));
      }else if(elasticityArr[i].substr(0,1) == '>'){
        objects['elasticity__gt'] = parseInt(elasticityArr[i].substr(1));
      }else if(elasticityArr[i].substr(0,1) == 'r'){
        objects['elasticity__range'] = elasticityArr[i].substr(1);
      }
    }
  }

  console.log(objects);

  wx.BaaS.getRecordList(objects).then( (res) => {
    // success
    console.log(res);
    that.setData({
      loadHide: true,
      filterCatHide:true,
      filterFiltHide:true,
      pageNo: that.data.pageNo+1,
      totalPage: Math.ceil(res.data.meta.total_count/that.data.pageSize),
      totalNum : res.data.meta.total_count
    });
    if(isRefresh){
      // 重新加载
      that.setData({
        productList: res.data.objects
      });
    }else{
      var productList = that.data.productList;
      for(var i=0; i<res.data.objects.length; i++){
        productList.push(res.data.objects[i]);
      }
      that.setData({
        productList: productList
      });
    }
  }, (err) => {
    // err
  });
}

var search = function(that, isRefresh){
  if(!isRefresh && that.data.pageNo != 0 && that.data.pageNo >= that.data.totalPage){
    that.setData({
          loadHide: true
    });
    return;
  }
  that.setData({
      loadHide: false
  });

  var pageNum = isRefresh ? 0 : that.data.pageNo; // 页码
  var limit = that.data.pageSize;
  var offset = limit * pageNum;
  var objects = {
    // tableID: getApp().globalData.TABLE_ID_PRODUCT,
    // status: 'valid',
    // limit: limit,
    // offset: offset
  };
  if(that.data.searchType == 1){
    // 成衣 搜索
    //objects['title__contains'] = that.data.keyword;
    objects['query'] = {
      "and": [
        { "status": 'valid'},
        { "category_id__in": [getApp().globalData.ALL_CATEGORY_ID.toString()]},
        {'or': [{ "title__contains": that.data.keyword }, { "subtitle__contains": that.data.keyword}]}
      ]
    };
    //objects['category_id__in'] = getApp().globalData.ALL_CATEGORY_ID;
  }else if(that.data.searchType == 2){
    // 面料 搜索
    objects['query'] = {
      "and": [
        { "status": 'valid' },
        { "category_id__in": [getApp().globalData.FABRIC_CATEGORY_ID.toString()] },
        { 'or': [{ "title__contains": that.data.keyword }, { "description__contains": that.data.keyword }] }
      ]
    };
    //  objects['title__contains'] = that.data.keyword;
    //  objects['category_id__in'] = getApp().globalData.FABRIC_CATEGORY_ID;
  }else if(that.data.searchType == 3){
    // 成衣扫码搜索
    objects['query'] = {
      "and": [
        { "status": 'valid' },
        { "category_id__in": [getApp().globalData.ALL_CATEGORY_ID.toString()] },
        { 'or': [{ "title__contains": that.data.keyword }, { "subtitle__contains": that.data.keyword }] }
      ]
    };
    // objects['subtitle'] = that.data.keyword;
    // objects['category_id__in'] = getApp().globalData.ALL_CATEGORY_ID;
  }else if(that.data.searchType == 4){
    // 面料扫码搜索
    objects['query'] = {
      "and": [
        { "status": 'valid' },
        { "category_id__in": [getApp().globalData.FABRIC_CATEGORY_ID.toString()] },
        { 'or': [{ "title__contains": that.data.keyword }, { "description__contains": that.data.keyword }] }
      ]
    };
    // objects['subtitle'] = that.data.keyword;
    // objects['category_id__in'] = getApp().globalData.FABRIC_CATEGORY_ID;
  }

  wx.BaaS.request({
    url: '/hserve/v1/table/' + getApp().globalData.TABLE_ID_PRODUCT + '/query/?limit=' + limit + '&offset=' + offset,
    method: 'POST',
    data: objects
  }).then((res) => {
    // success
    console.log(res);
    that.setData({
      loadHide: true,
      filterCatHide: true,
      filterFiltHide: true,
      pageNo: that.data.pageNo + 1,
      totalPage: Math.ceil(res.data.meta.total_count / that.data.pageSize),
      totalNum: res.data.meta.total_count
    });
    if (res.data.meta.total_count == 0) that.setData({ isEmpty: true });
    if (isRefresh) {
      // 重新加载
      that.setData({
        productList: res.data.objects
      });
    } else {
      var productList = that.data.productList;
      for (var i = 0; i < res.data.objects.length; i++) {
        productList.push(res.data.objects[i]);
      }
      that.setData({
        productList: productList
      });
    }
  }, (err) => {
    // err
  });
}
var getProductInfo = function(productId, callBack){
  var objects = {
    tableID : getApp().globalData.TABLE_ID_PRODUCT,
    recordID : productId,
    status: 'valid'
  };
  wx.BaaS.getRecord(objects).then( (res) => {
    // success
    if(callBack) callBack(res.data);
  }, (err) => {
    // err
  });
}

var getClothRelate = function(productId, parentId, num, callBack){
  // 获取相关成衣， parentId 成衣使用面料产品ID
  // 拉回来一部分
  var objects = {
    tableID : getApp().globalData.TABLE_ID_PRODUCT,
    category_id__in : getApp().globalData.ALL_CATEGORY_ID,
    parent_id : parentId,
    limit : getApp().globalData.relateBathNum,
    status: 'valid',
    offset : 0 
  };
  wx.BaaS.getRecordList(objects).then( (res) => {
    // success
    var objects = new Array();
    // 剔除本身
    for(var i = 0; i < res.data.objects.length; i++){
      if(res.data.objects[i].id != productId) objects.push(res.data.objects[i]);
    }
    // 随机num个
    if(objects.length <= num ){
      if(callBack) callBack(objects);
    }else{
      // 随机找num个
      var randomArr = util.randomNumArr(0, objects.length-1, num);
      var newObjects = new Array();
      for(var i = 0; i < randomArr.length; i++){
          newObjects.push(objects[i]);
      }
      if(callBack) callBack(newObjects);
    }
    
  }, (err) => {
    // err
  });
}

var getFabricRelate = function(productId, component, num, callBack){
  // 获取相关面料
  // 拉回来一部分
  var componentIds = '';
  for(var i = 0; i < component.length; i++){
    if(componentIds == ''){
      componentIds =  component[i];
    }else{
      componentIds += ',' + component[i];
    }
  }
  var objects = {
    tableID : getApp().globalData.TABLE_ID_PRODUCT,
    category_id__in : getApp().globalData.FABRIC_CATEGORY_ID,
    component__in : componentIds,
    status: 'valid',
    limit : 0,
    offset : getApp().globalData.relateBathNum
  };
  wx.BaaS.getRecordList(objects).then( (res) => {
    // success
    var objects = new Array();
    // 剔除本身
    for(var i = 0; i < res.data.objects.length; i++){
      if(res.data.objects[i].id != productId) objects.push(res.data.objects[i]);
    }
    // 随机num个
    if(objects.length <= num ){
      if(callBack) callBack(objects);
    }else{
      // 随机找num个
      var randomArr = util.randomNumArr(0, objects.length-1, num);
      var newObjects = new Array();
      for(var i = 0; i < randomArr.length; i++){
          newObjects.push(objects[i]);
      }

      if(callBack) callBack(newObjects);
    }
  }, (err) => {
    // err
  });
}

var getFabricCloth = function(productId, num, callBack){
  // 获取面料所做的成衣; 该面料所做的成衣，显示最新发布的前 6 位
  var objects = {
    tableID : getApp().globalData.TABLE_ID_PRODUCT,
    category_id__in : getApp().globalData.ALL_CATEGORY_ID,
    parent_id : productId,
    order_by: '-created_at',
    status: 'valid',
    limit: num,
    offset: 0
  };
  wx.BaaS.getRecordList(objects).then( (res) => {
    // success
    callBack(res.data.objects);
  }, (err) => {
    // err
  });
}

var checkFavorite = function(productId, callBack){
  var objects = {
    tableID : getApp().globalData.TABLE_ID_PRODUCT_FAVORITE,
    product_id : productId,
    created_by: getApp().globalData.userInfo.userId
  };
  wx.BaaS.getRecordList(objects).then( (res) => {
    // success
    res.data.objects.length > 0 ? callBack(res.data.objects[0].id) : callBack(0);
  }, (err) => {
    // err
  });
};
var favorite = function(productId, opType, favoriteId, callBack){
  var opType = opType ? 1 : 2; // 1-收藏;2-取消收藏
  if(opType == 1){
      let tableID = getApp().globalData.TABLE_ID_PRODUCT_FAVORITE;
      let data = {
        product_id: productId
      };
      let objects = {
        tableID,
        data
      };
      wx.BaaS.createRecord(objects).then( (res) => {
        console.log(res);
        if(callBack) callBack(res.data.id);
      }, (err) => {
        // err
      });
  }else{
    // 删除掉
    let tableID = getApp().globalData.TABLE_ID_PRODUCT_FAVORITE;
    let recordID = favoriteId;
    let objects = {
      tableID,
      recordID
    };
    wx.BaaS.deleteRecord(objects).then( (res) => {
      // success
      callBack(0);
    }, (err) => {
      // err
    });
  }
}

var placeOrder = function(items, orderOkCallBack, failCallBack){
  // 下订单 productid_typeid:num
  var length = 0;
  for(var i in items){
    if(items.hasOwnProperty(i)) length++;
  }

  if(length == 0) return;

  wx.request({
    url: getApp().globalData.API_URL,
    data: items,
    method: 'GET',
    success: function(res){
      // success
      if(orderOkCallBack) orderOkCallBack(res.data);
    },
    fail: function(e) {
      // fail
      if(failCallBack) failCallBack(e);
    }
  })
}

var getVendorInfo = function(vendorId, callBack){
  // 找到供应商信息
  var objects = {
    tableID : getApp().globalData.TABLE_ID_VENDOR,
    recordID : vendorId
  };
  wx.BaaS.getRecord(objects).then( (res) => {
    // success
    if(callBack) callBack(res.data);
  }, (err) => {
    // err
  });
}

var getProductSKU = function(productId, callBack){
  let objects = {
    tableID: getApp().globalData.TABLE_ID_PRODUCT_SKU,
    product_id: productId
  };
  wx.BaaS.getRecordList(objects).then( (res) => {
    // success
    console.log(res);
    if(callBack) callBack(res.data.objects);
  }, (err) => {
    // err
  });  
}

module.exports = {

  getChildCategory: getChildCategory,

  getClothList : getClothList,
  getProductInfo : getProductInfo,

  getClothRelate: getClothRelate,
  getFabricRelate: getFabricRelate,
  getFabricCloth: getFabricCloth,

  search: search,
  checkFavorite: checkFavorite,
  favorite: favorite,

  getVendorInfo: getVendorInfo,
  getProductSKU: getProductSKU,

  placeOrder: placeOrder
}